const router = require('koa-router')()
const token = require('../middleware/token')
const Main = require('../dbs/models/main')
const Record = require('../dbs/models/record')
const Menu = require('../dbs/models/menu')
const Content = require('../dbs/models/content')


const User = require('../dbs/models/user')
const jwt = require('jsonwebtoken')
const output = require('../middleware/output')
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})
router.get('/string', async (ctx, next) => {
  let a = {name:'张三',admin:true};
  let secret = 'I_LOVE_JING';
  let token = jwt.sign(a,secret, { expiresIn: 60 });
  let payload = jwt.verify(token,secret)
  global.console.log(payload)
  // global.console.log(token)
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/main', async(ctx) => {
  try {
    const data = await Main.find()
    ctx.body = {
      code: 0,
      data
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      error
    }
  }
})

router.get('/test', async(ctx) => {
  let status = await token(ctx)
  if (status === 0) {

    ctx.body = {
      code: 0,
      msg: '成功'
    }
  } else if (status === 10001) {
    ctx.body = {
      code: 10001,
      msg: 'token已过期请重新登陆'
    }
  }
})

router.get('/testAsync', async (ctx, next) => {
  const a = await new Promise((resolve) => {
    setTimeout(() => {
      resolve('taosong ai weiqi')
    }, 3000)
  })
  ctx.body = {
    a
  }
})
/** 查询搜索记录 */
router.post('/querySearchRecord', async (ctx) => {
  let { username } = ctx.request.body
  let msg, code
  try {
    let result = await Record.findOne({ username })
    ctx.body = {
      result,
      code: 0,
      msg: '获取成功'
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: error
    }
  }
  
})

/** 保存搜索记录限制五条搜索记录一直增加就删前增后 */
router.post('/addSearchList', async (ctx) => {
  let information = ctx.request.body
  let code, msg
  let status = await token(ctx)
  if (status === 0) {
    let result = await Record.find({username: information.username})
    let list 
    if (result.length !== 0) {
      list = result[0].searchHistory
      if (list.length === 6) {
        list = list.slice(1,6)
      }
      let flag = false
      list.forEach(item => {
        if (information.content === item) {
          flag = true
        }
      })
      !flag ? 
        await Record.update({username: information.username}, {searchHistory: [...list, information.content]}) : 
        ''
    } else {
      list = []
      const record = await Record({
        username: information.username,
        searchHistory: [...list, information.content]
      });
      await record.save()
    }
    ctx.body = {
      code: 0,
      msg: '成功'
    }
  } else if (status === 10001) {
    ctx.body = {
      code: 10001,
      msg: 'token已过期请重新登陆'
    }
  }
})

/** 删除搜索历史 */
router.get('/deleteSearchHistory', async (ctx) => {
  let status = await token(ctx)
  if (status === 0) {
    await Record.update({username: ctx.query.username}, {searchHistory: []})
    ctx.body = {
      code: 0,
      msg: '成功'
    }
  } else if (status === 10001) {
    ctx.body = {
      code: 10001,
      msg: 'token已过期请重新登陆'
    }
  }
})

/** 获取菜单内容 */
router.get('/menu', async (ctx) => {
  let code
  try {
    let data = await Menu.find()
    ctx.body = {
      code: 0,
      data
    }
  } catch (error) {
    ctx.body = {
      code: -1,
    }
  }
})

/** 查询首页其他数据 */
router.get('/otherData', async (ctx) => {
  let code, msg, data
  try {
    data = await Content.findOne()
    code = 0
    msg = '成功'
  } catch (error) {
    code = 1
    msg = '失败'
  }
  ctx.body = {
    code, 
    msg,
    data
  }
})

module.exports = router
